<template>
  <div class="form-box">
    <div class="form-main">
      <!-- readerModel -->
      <template v-if="node.nodeType === 'reader'">
        <p class="header">节点配置</p>
        <el-form :model="readerKAFKAForm" :rules="rules" ref="readerKAFKAForm" label-width="140px">
          <el-form-item label="数据源" prop="datasourceId" required>
            <el-select v-model="readerKAFKAForm.datasourceId" placeholder="请选择">
              <el-option
                v-for="item in datasourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="topics" prop="topics" required>
            <el-input v-model="readerKAFKAForm.topics"></el-input>
          </el-form-item>
          <el-form-item label="maxBytes" prop="maxBytes">
            <el-input v-model="readerKAFKAForm.maxBytes" type="number"></el-input>
          </el-form-item>
          <el-form-item label="maxOffsetPertrigger" prop="maxOffsetPertrigger">
            <el-input v-model="readerKAFKAForm.maxOffsetPertrigger" type="number"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <!-- filterModel -->
      <template v-if="node.nodeType === 'filter'">
        <template v-if="node.type == 1">
          <p class="form-empty">无配置项</p>
        </template>
        <template v-else>
          <!-- 节点配置 -->
          <p class="header">节点配置</p>
          <el-form :model="filterForm" :rules="rules" ref="filterForm" label-width="120px">
            <!-- <el-form-item label="sql" prop="sql" required>
              <el-input v-model="filterForm.sql"></el-input>
            </el-form-item> -->
            <el-form-item label="decoderClass" prop="decoderClass" required>
              <el-input v-model="filterForm.decoderClass"></el-input>
            </el-form-item>
          </el-form>
          <!-- 输出字段 -->
          <p class="header">输出字段</p>
          <div class="table-box">
            <div class="form-table">
              <div class="table-header table-tr">
                <p class="tr-cell tr-left">字段名</p>
                <p class="tr-cell tr-center">类型</p>
                <p class="tr-cell tr-right" v-show="fileldList.length > 1">操作</p>
              </div>
              <div class="table-tr" v-for="(field, index) in fileldList" :key="index">
                <el-input class="tr-cell tr-left" v-model="field.value" placeholder="请输入字段名" @input="changeField"></el-input>
                <el-select class="tr-cell tr-center" v-model="field.type" placeholder="请选择字段类型" @change="changeField">
                  <el-option
                    v-for="item in fieldTypesOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <i v-show="fileldList.length > 1" class="el-icon-circle-close tr-cell tr-right tr-icon" @click="deletField(index)"></i>
              </div>
            </div>
            <p class="error-msg">{{errMsg}}</p>
            <span class="add-tr" @click="addField"><i class="el-icon-circle-plus-outline"></i> 添加字段</span>
          </div>
        </template>
      </template>
      <!-- writerModel -->
      <template v-if="node.nodeType === 'writer'">
        <p class="header">节点配置</p>
        <!-- kafkaModel -->
        <el-form v-if="node.name === 'KAFKA'" :model="writerKAFKAForm" :rules="rules" ref="writerKAFKAForm" label-width="80px">
          <el-form-item label="数据源" prop="datasourceId" required>
            <el-select v-model="writerKAFKAForm.datasourceId" placeholder="请选择">
              <el-option
                v-for="item in datasourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="topic" prop="topic" required>
            <el-input v-model="writerKAFKAForm.topic"></el-input>
          </el-form-item>
          <el-form-item label="acks" prop="acks" required>
            <el-select v-model="writerKAFKAForm.acks" placeholder="请选择">
              <el-option
                v-for="item in acksOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- hiveModel -->
        <el-form v-if="node.name === 'HIVE'" :model="writerHIVEForm" :rules="rules" ref="writerHIVEForm" label-width="100px">
          <el-form-item label="数据源" prop="datasourceId" required>
            <el-select v-model="writerHIVEForm.datasourceId" placeholder="请选择">
              <el-option
                v-for="item in datasourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="database" prop="database" required>
            <el-input v-model="writerHIVEForm.database"></el-input>
          </el-form-item>
          <el-form-item label="table" prop="table" required>
            <el-input v-model="writerHIVEForm.table"></el-input>
          </el-form-item>
          <el-form-item label="partitionBy" prop="partitionBy">
            <el-input v-model="writerHIVEForm.partitionBy"></el-input>
          </el-form-item>
          <el-form-item label="repartitions" prop="repartitions">
            <el-input v-model="writerHIVEForm.repartitions" type="number"></el-input>
          </el-form-item>
          <el-form-item label="format" prop="format" required>
            <el-select v-model="writerHIVEForm.format" placeholder="请选择">
              <el-option
                v-for="item in formatOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="cleanTable" prop="cleanTable" required>
            <el-switch
              v-model="writerHIVEForm.cleanTable"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item label="coverTable" prop="coverTable" required>
            <el-switch
              v-model="writerHIVEForm.coverTable"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item> -->
        </el-form>
        <!-- dorisModel -->
        <el-form v-if="node.name === 'DORIS'" :model="writerDORISForm" :rules="rules" ref="writerDORISForm" label-width="100px">
          <el-form-item label="数据源" prop="datasourceId" required>
            <el-select v-model="writerDORISForm.datasourceId" placeholder="请选择">
              <el-option
                v-for="item in datasourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="table" prop="table" required>
            <el-input v-model="writerDORISForm.table"></el-input>
          </el-form-item>
        </el-form>
        <!-- esModel -->
        <el-form v-if="node.name === 'ES'" :model="writerESForm" :rules="rules" ref="writerESForm" label-width="100px">
          <el-form-item label="数据源" prop="datasourceId" required>
            <el-select v-model="writerESForm.datasourceId" placeholder="请选择">
              <el-option
                v-for="item in datasourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="index" prop="index" required>
            <el-input v-model="writerESForm.index"></el-input>
          </el-form-item>
          <el-form-item label="index_type" prop="index_type" required>
            <el-input v-model="writerESForm.index_type"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { Promise } from 'q';
export default {
  name: "DataForm",
  data() {
    return {
      // reader-kafkaModel
      readerKAFKAForm:{
        topics: "",
        maxBytes: 0, //数字类型 非必填 默认0或空
        datasourceId: '', // 数据源
        maxOffsetPertrigger: 20000, // 非必填 默认20000
      },
      // filterModel
      filterForm:{
        // sql: "", //  type = 3才出现
        fieldTypes: "", // 选择（后端返回类型）后拼接
        decoderClass: ""
      },
      // write-kafkaModel
      writerKAFKAForm: {
        acks: '1',
        topic: "",
        datasourceId: '',
      },
      // writer-hiveModel
      writerHIVEForm: {
        table: "",
        database: "",
        format: "parquet",
        cleanTable: false,
        coverTable: false,
        partitionBy: "",
        datasourceId: '',
        repartitions: '',
      },
      // writer-esModel
      writerESForm:{
        index: "",
        index_type: "",
        datasourceId: '',
      },
      // write-dorisModel
      writerDORISForm: {
        table: "",
	      datasourceId: '',
      },
      datasourceOptions: [], // 数据源类型
      fieldTypesOptions: [], // 字段类型
      formatOptions: [ 'parquet', 'orc'], 
      acksOptions: ['1', '-1'],
      fileldList: [
        {
          value: '',
          type: ''
        }
      ],
      errMsg: ''
    }
  },
  props: {
    node: Object,
    project_id: Number
  },
  computed: {
    ...mapState({
      currentTab: ({ data }) => data.currentTab
    }),
    formName() {
      const {name, nodeType} = this.node
      if(nodeType === 'filter') {
        return 'filterForm'
      } else {
        return `${nodeType}${name}Form`
      }
    },
    mainName() {
      return this.node.nodeType + 'Model'
    },
    subNmae() {
      return this.node.name.toLowerCase() + 'Model'
    }
  },
  mounted() {
    if(this.currentTab.param) {
      this.init()
    }
    this.$nextTick(() => {
      this.getDatasources()
      this.getFeldtypes()
    })
  },
  methods: {
    init() {
      const {writerModel = {}, filterModel = {}, readerModel = {}} = this.currentTab.param
      const {nodeType, type} = this.node
      if(nodeType === 'filter' && filterModel.type == type) {
        if(type == 1) {
          return false
        } else {
          this.filterForm = filterModel
          this.fileldList = filterModel.fieldTypes.split(',').map((item, index) => {
            let arr = item.split(':')
            let obj = {
              value: arr[0],
              type: arr[1]
            }
            return obj
          })
        }
      } 
      if(nodeType === 'reader' && readerModel.type == type) {
        this[this.formName] = readerModel[this.subNmae]
      } 
      if(nodeType === 'writer' && writerModel.type == type){
        this[this.formName] = writerModel[this.subNmae]
      }
    },
    getDatasources(){
      this.$http.task.datasources({
        type: this.node.type,
        project_id: this.project_id
      }).then(res => {
        this.datasourceOptions = res
      })
    },
    getFeldtypes(){
      this.$http.task.fieldtypes()
        .then(res => {
          this.fieldTypesOptions = res
        })
    },
    addField() {
      let obj = {
        value: '',
        type: ''
      }
      this.fileldList.push(obj)
      this.errMsg = ''
    },
    deletField(index) {
      this.errMsg = ''
      this.fileldList.splice(index, 1)
    },
    changeField() {
      this.errMsg = ''
    },
    // filter模型 输出字段 校验
    async validateFileld() {
      let arr = []
      this.fileldList.every((item, i) => {
        if(item.value === '' || item.type === '') {
          this.errMsg = `请完善字段信息`
          return false
        } else {
          arr[i] = `${item.value}:${item.type}`
        }
        return item.value !== '' && item.type !== ''
      })
      return arr
    },
    validate() {
      let param = {}
      const {node, mainName, formName, subNmae } = this
      const {nodeType, name, type} = node
      return new Promise((res, rej) => {
        if(mainName === 'filterModel') {
        // filter模型校验
          this.errMsg = ''
          // 节点设置校验
          if(type == 1) {
            param = {
              [mainName]: {
                type,
              }
            }
            res(true)
            // 提交表单信息
            this.$emit('submit', param)
          } else {
            this.$refs[formName].validate(async (valid) => {
              if(valid) {
                let arr = await this.validateFileld()
                if(this.errMsg) {
                  this.$message.warning(`请完善${nodeType}-${name}信息`)
                  res(false)
                } else {
                  this.filterForm.fieldTypes = arr.join(',')
                  param = {
                    [mainName]: {
                      type,
                      ...this[formName]
                    }
                  }
                  // 提交表单信息
                  this.$emit('submit', param)
                  res(true)
                }
              } else {
                this.validateFileld()
                this.$message.warning(`请完善${nodeType}-${name}信息`)
                res(false)
              }
            })
          }
        } else {
        // reader writer 模型校验
          this.$refs[formName].validate((valid) => {
            if (valid) {
              param = {
                [mainName]: {
                  type,
                  [subNmae]: this[formName]
                }
              }
              this.$emit('submit', param)
              res(true)
            } else {
              this.$message.warning(`请完善${nodeType}-${name}信息`)
              res(false)
            }
          })
        }
      })
    }
  }
}  
</script>

<style lang="scss">
$border-color: #e4e7ed;
$border: 1px solid $border-color;
.form-box{
  height: 100%;
  overflow-y: scroll;
  padding-bottom: 20px;
  box-sizing: border-box;
  .header{
    line-height: 14px;
    font-size: 14px;
    font-weight: bold;
    padding: 0 10px;
    border-left: 3px solid #409eff;
  }
  .form-empty{
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    color: #999;
  }
  .table-box{
    // display: flex;
    // align-items: flex-end;
    .form-table{
      // flex: 1;
      border-top: $border;
      border-left: $border;
      border-right: $border;
      .table-header {
        background: #f8f8f9;
        line-height: 40px;
        font-size: 14px;
        font-weight: bold;
        color: #515a6e;
        p{
          padding: 0;
          margin: 0;
        }
      }
      .table-tr{
        display: flex;
        align-items: center;
        border-bottom: $border;
        // height: 40px;
      }
      .tr-cell{
        text-align: center;
      }
      .tr-left, .tr-center{
        flex: 1;
        border-right: $border;
        padding: 10px;
      }
      .tr-right{
        width: 60px;
      }
    }
    .tr-icon{
      font-size: 24px;
      color: #999;
      cursor: pointer;
      &:hover{
        color: #409eff;
      }
    }
    .error-msg{
      color: #F56C6C;
    }
    .add-tr{
      font-size: 14px;
      color: #409eff;
      cursor: pointer;
    }
  }
  
}
</style>